<template>
	<a-form ref="mobile" :model="formData" :rules="formRules" layout="vertical" class="form-box">
		<a-row :gutter="75">
			<a-col :span="8">
				<a-form-item label="版本号" name="appVersion">
					<a-input v-model:value="formData.appVersion" placeholder="请输入版本号" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="版本说明" name="appVersionNote">
					<a-input v-model:value="formData.appVersionNote" placeholder="请输入版本说明不超过30字" :maxlength="30" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="packageName" name="packageName">
					<a-input v-model:value="formData.packageName" placeholder="请输入" />
				</a-form-item>
			</a-col>
		</a-row>
		<a-row :gutter="75">
			<a-col :span="8">
				<a-form-item label="activityName" name="activityName">
					<a-input v-model:value="formData.activityName" placeholder="请输入" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="上传客户端" name="appUrl">
					<!-- <a-textarea v-model:value="formData.appUrl" placeholder="请输入上传客户端" /> -->
					<a-upload v-model:file-list="fileList1" accept=".apk" :max-count="1" @remove="remove"
						:customRequest="customRequestStroe">
						<a-button>
							<upload-outlined></upload-outlined>
							上传文件
						</a-button>
					</a-upload>
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="名单权限" name="permission">
					<a-radio-group v-model:value="formData.permission" :options="radioOption" />
				</a-form-item>
			</a-col>
		</a-row>
		<a-row :gutter="75">
			<a-col :span="8" v-if="editDate">
				<a-form-item label="移动端appId" name="appAppId">
					<a-input v-model:value="formData.appAppId" disabled />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="应用logo" name="appLogo">
					<div class="upload-box">
						<a-upload v-model:file-list="fileList" name="avatar" list-type="picture-card"
							class="avatar-uploader" :customRequest="customRequest" :accept="fileImgType"
							:before-upload="beforeUpload" @change="handleChange" @preview="handlePreview">
							<div v-if="fileList?.length == 0">
								<plus-outlined></plus-outlined>
								<div class="ant-upload-text">上传图片</div>
							</div>
						</a-upload>
						<div class="annotation">
							<div class="tit1">*注</div>
							<div>1.应用logo需要满足UI/UE规范;</div>
							<div>2.需要上传.png/.jpg/.jpeg格式文件;</div>
							<div>3.文件大小为不超过200K;</div>
						</div>
					</div>
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="参数信息" name="param">
					<a-textarea v-model:value="formData.param" placeholder="请输入参数信息" />
				</a-form-item>
			</a-col>
		</a-row>

		<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
			<img alt="example" style="width: 100%" :src="imageUrl" />
		</a-modal>
	</a-form>
</template>

<script setup name="MobileForm">
import fileApi from '@/api/dev/fileApi'
import tool from '@/utils/tool'
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const version = route.query.version
const fileUrl = import.meta.env.VITE_FILE_URL

const fileImgType = '.jpg,.png,.jpeg,'
const mobile = ref()
// 表单数据
const formData = ref({})

// 兼容行option
const compatibleOptions = ['IE8', 'IE9', 'IE10', 'IE11', 'chrome', 'firefox', '其他']
const validatePass = async (rule, value) => {
	const reg = /^([1-9]\d|[1-9])(\.([0-9]){1,3}){1,9}$/
	if (!value) {
		// callback(new Error('请输入密码'))
		return Promise.reject('请输入版本号')
	}
	if (!reg.test(value)) {
		return Promise.reject('请输入正确的版本号')
	}
	return Promise.resolve()
}
// 默认要校验的
const formRules = {
	name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
	appVersion: [{ required: true, validator: validatePass, tirgger: 'blur' }],
	appVersionNote: [{ required: true, message: '请输入版本说明', trigger: 'blur' }],
	packageName: [{ required: true, message: '请输入', trigger: 'blur' }],
	activityName: [{ required: true, message: '请输入', trigger: 'blur' }],
	appUrl: [{ required: true, message: '请上传客户端', trigger: 'blur' }],
	param: [{ required: true, message: '请输入参数信息', trigger: 'blur' }],
	appLogo: [{ required: true, message: '请选择logo', trigger: 'blur' }],
	permission: [{ required: true, message: '请选择权限名单', trigger: 'blur' }]
}

const fileList = ref([])
const fileList1 = ref([])
const loading = ref(false)
const imageUrl = ref('')
let previewVisible = ref(false)
// 单选option
const radioOption = [
	{ label: '全国', value: '0' },
	{ label: '白名单', value: '1' }
]

/*变更编辑  开始*/
const editDate = inject('editDate')
const setForm = (appPro) => {
	formData.value = appPro
	console.log(formData.value)
	if (appPro.appLogo && !appPro.appLogo.includes('store')) {
		//不是老数据
		fileList.value = appPro.appLogo ? JSON.parse(appPro.appLogo) : []
		fileList.value.forEach((item) => {
			item.url = `${fileUrl}/${item.url}`
		})
	}
	if (appPro.appUrl && appPro.appUrl.includes('name')) {
		//不是老数据
		fileList1.value = appPro.appUrl ? JSON.parse(appPro.appUrl) : []
		fileList1.value.forEach((item) => {
			item.url = `${fileUrl}/${item.url}`
		})
	}
}
if (editDate.value) {
	if (editDate.value.androidPropertiesList.length > 1) {
		// 多版本
		const appProperties = editDate.value.androidPropertiesList.find((v) => v.appVersion == version)
		setForm(appProperties)
	} else {
		setForm(editDate.value.androidPropertiesList[0])
	}
}
/*变更编辑  结束*/
// 自定义上传
const customRequest = (file) => {
	// 后端需要接受的参数是 formData数据，
	const form = new FormData()
	form.append('file', file.file)
	fileApi
		.uploadCosReturnUrlPub(form)
		.then((res) => {
			let arr = [{ name: file.file.name, url: res }]
			formData.value.appLogo = JSON.stringify(arr)
			file.onSuccess(res, file.file)
			file.status = 'done'
		})
		.catch((err) => {
			setTimeout(() => {
				file.onError()
			}, 1000)
		})
}

// 应用商店自定义上传（不带权限）
const customRequestStroe = (file) => {
	// 后端需要接受的参数是 formData数据，
	const form = new FormData()
	form.append('file', file.file)
	fileApi.uploadCosReturnUrlPub(form).then((res) => {
		let arr = [{ name: file.file.name, url: res }]
		formData.value.appUrl = JSON.stringify(arr)
		file.onSuccess(res, file.file)
		file.status = 'done'
	})
}
const remove = () => {
	formData.value.appUrl = ''
}
const getBase64 = (img, callback) => {
	const reader = new FileReader()
	reader.addEventListener('load', () => callback(reader.result))
	reader.readAsDataURL(img)
}
const handleChange = (info) => {

	const { type, size } = info.file
	const isJpgOrPng = type === 'image/jpeg' || type === 'image/png' || type === 'image/jpg'
	const isLt2K = size / 1024 < 200
	if (!isJpgOrPng) {
		message.warning('图片类型不对')
		fileList.value = []
		return false
	}
	if (!isLt2K) {
		message.warning('图片大小不超过200K')
		fileList.value = []
		return false
	}
	if (info.file.status === 'uploading') {
		loading.value = true
		return
	}



	if (info.file.status === 'uploading') {
		loading.value = true
		return
	}
	if (info.file.status === 'done') {
		// Get this url from response in real world.
		getBase64(info.file.originFileObj, (base64Url) => {
			imageUrl.value = base64Url
			loading.value = false
		})
	}
	if (info.file.status === 'error') {
		loading.value = false
		fileList.value = []
		// message.error('upload error')
	}
	if (info.file.status === 'removed') {
		formData.value.appLogo = ''
	}
}
const beforeUpload = (file) => {
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
	const isLt2K = file.size / 1024 < 200
	return isJpgOrPng && isLt2K
}
const handlePreview = () => {
	previewVisible.value = true
}
const handleCancel = () => {
	previewVisible.value = false
}

// 表单验证
const handleValidate = () => {
	return new Promise((resolve, reject) => {
		mobile.value
			.validate()
			.then(() => {
				console.log('成功')
				resolve(formData.value)
			})
			.catch(() => {
				console.log('失败')
				resolve(false)
			})
	})
}
defineExpose({ handleValidate })
</script>


<style lang="less" scoped>
.form-box {
	margin-top: 14px;

	.upload-box {
		display: flex;

		.annotation {
			font-size: 12px;
			color: rgb(150, 150, 150);
			line-height: 22px;
			margin-left: 10px;

			.tit1 {
				color: rgb(194, 0, 0);
			}
		}
	}

	&-inp {
		border-radius: 4px;
		border: 1px solid rgb(206, 206, 206);
	}
}
</style>
<style>
.avatar-uploader>.ant-upload {
	width: 104px;
	height: 104px;
}

.ant-upload-select-picture-card i {
	font-size: 32px;
	color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
	margin-top: 8px;
	color: #666;
}

.upload-box>.ant-upload-picture-card-wrapper {
	width: unset;
}
</style>
